package com.utils;

import com.model.dos.CompetitionDO;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import com.opencsv.exceptions.CsvValidationException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *   文件工具类
 * </p>
 * @author 34448
 */
public class FileUtils {

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 从文件中读取比赛信息
     * @param filePath 文件路径
     * @return 比赛信息列表
     * @throws IOException 读取文件异常
     */
    public static List<CompetitionDO> readCompetitionsFromFile(String filePath) throws IOException {
        List<CompetitionDO> competitions = new ArrayList<>();
        try (CSVReader reader = new CSVReader(new FileReader(filePath))) {
            String[] line;
            while ((line = reader.readNext()) != null) {
                CompetitionDO competitionDO = new CompetitionDO();
                competitionDO.setCompetitionName(line[1]);
                try {
                    competitionDO.setCompetitionDate(DATE_FORMAT.parse(line[2]));
                } catch (ParseException e) {
                    throw new IOException("日期解析失败", e);
                }
                competitionDO.setLocation(line[3]);
                competitionDO.setDescription(line[4]);
                competitions.add(competitionDO);
            }
        } catch (CsvValidationException e) {
            throw new IOException("CSV文件验证失败", e);
        }
        return competitions;
    }

    /**
     * 将比赛信息写入文件
     * @param filePath 文件路径
     * @param competitions 比赛信息列表
     * @throws IOException 写入文件异常
     */
    public static void writeCompetitionsToFile(String filePath, List<CompetitionDO> competitions) throws IOException {
        try (CSVWriter writer = new CSVWriter(new FileWriter(filePath))) {
            for (CompetitionDO competition : competitions) {
                String[] line = new String[]{
                        String.valueOf(competition.getCompetitionId()),
                        competition.getCompetitionName(),
                        DATE_FORMAT.format(competition.getCompetitionDate()),
                        competition.getLocation(),
                        competition.getDescription()
                };
                writer.writeNext(line);
            }
        }
    }
}